#!/bin/bash

# ha_1, ha_2 配置相同

vip_1=192.168.2.100
host_1_ip_0=192.168.2.71
host_1_ip_1=192.168.11.71

vip_2=192.168.11.100
host_2_ip_0=192.168.2.72
host_2_ip_1=192.168.11.72

# 安装依赖环境
yum install -y gcc gcc-c++ glibc glibc-devel pcre pcre-devel openssl  openssl-devel systemd-devel net-tools \
  vim iotop bc zip unzip zlib-devel lrzsz tree screen lsof tcpdump wget ntpdate

# 下载解压编译安装
wget https://github.com/haproxy/haproxy/archive/v1.8.0.tar.gz -O hayroxy-1.8.0.tar.gz
tar xvf hayroxy-1.8.0.tar.gz -C /usr/local/src
cd /usr/local/src/haproxy-1.8.0/
make  ARCH=x86_64 TARGET=linux2628 USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 USE_SYSTEMD=1  USE_CPU_AFFINITY=1  PREFIX=/usr/local/haproxy
make install PREFIX=/usr/local/haproxy

# 创建服务
cat <<'EOF'    >/usr/lib/systemd/system/haproxy.service
[Unit]
Description=HAProxy Load Balancer
After=syslog.target network.target

[Service]
# 支持多配置文件读取，类似于从侧面是实现配置文件的include功能
ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -f /etc/haproxy/conf -c -q
ExecStart=/usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -f /etc/haproxy/conf -p /run/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID

[Install]
WantedBy=multi-user.target
EOF

cp haproxy  /usr/sbin/
mkdir /usr/local/haproxy/run/
mkdir -p /etc/haproxy/conf

# 创建资源配置
cat <<EOF  >/etc/haproxy/haproxy.cfg
global
maxconn 100000
chroot /usr/local/haproxy
#stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin
uid 99
gid 99
daemon
nbproc 4
cpu-map 1 0
cpu-map 2 1
cpu-map 3 2
cpu-map 4 3
pidfile /usr/local/haproxy/run/haproxy.pid
log 127.0.0.1 local3 info

defaults
option http-keep-alive
option  forwardfor
maxconn 100000
mode http
timeout connect 300000ms
timeout client  300000ms
timeout server  300000ms

listen stats
    mode http
    bind 0.0.0.0:9999
    stats enable
    log global
    stats uri     /haproxy-status
    stats auth    haadmin:111111
EOF

cat <<EOF    >/etc/haproxy/conf/openstack.cfg
listen  openstack_port
    bind ${vip_1}:80
    mode http
    log global
    server ${host_1_ip_0}  ${host_1_ip_0}:80  check inter 3000 fall 2 rise 5
    server ${host_2_ip_0}  ${host_2_ip_0}:80  check inter 3000 fall 2 rise 5
EOF

# 修改内核参数(当本地不存在vip时依旧监听端口)
echo """
net.ipv4.ip_nonlocal_bind = 1
net.ipv4.ip_forward = 1
"""  >>/etc/sysctl.conf
sysctl -p

# 启动服务跟随系统启动
systemctl start haproxy
systemctl enable haproxy